/*
 * @Description:
 * @Author: 胡涛
 * @Date: 2023-06-06 09:09:08
 * @LastEditors: 胡涛
 * @LastEditTime: 2023-11-12 14:02:19
 */
import { storeToRefs } from "pinia";
import { createRouter, createWebHashHistory } from "vue-router";
import { useAppStore } from "../store";
import { routes } from "./config";
import { checkPermission } from "@/helpers";
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

const isAuthenticated = () => {
  const { token } = storeToRefs(useAppStore());
  return token.value && token.value.trim() !== "";
};

router.beforeEach(async (to, _, next) => {
  if (to.meta.allowAnonymous === true) {
    next();
  } else if (!isAuthenticated()) {
    next({ path: "/login", query: { redirectUrl: to.fullPath } });
  } else {
    let name: string = to.meta.permissionCode as string;
    console.log("beforeEach", name, checkPermission(name));
    if (!name || checkPermission(name)) {
      next();
    } else {
      next({ path: "/403", query: { redirectUrl: to.fullPath } });
    }
  }
});

export default router;
